import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

const request = axios.create({
  baseURL: '/api',  // 使用 vite proxy 配置
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 优先从 localStorage 获取 token，确保刷新后也能正常工作
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('Request with token:', config.url)
    } else {
      console.log('Request without token:', config.url)
    }
    return config
  },
  error => {
    console.error('Request interceptor error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    console.log('Response received:', response.config.url, response.status)
    return response.data
  },
  error => {
    console.error('Response error:', error.config?.url, error.response?.status, error.message)
    
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('未授权，请重新登录')
          const authStore = useAuthStore()
          authStore.logout()
          router.push('/login')
          break
        case 403:
          ElMessage.error('拒绝访问')
          break
        case 404:
          ElMessage.error('请求错误，未找到该资源')
          break
        case 500:
          ElMessage.error('服务器错误')
          break
        default:
          const errorMsg = error.response.data?.message || error.response.data?.detail || '请求失败'
          ElMessage.error(errorMsg)
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    return Promise.reject(error)
  }
)

export default request